package com.wave.wavesystem.ai.service.impl;

import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;

import com.wave.common.enums.ErrorCode;
import com.wave.common.exception.WaveException;
import com.wave.wavesystem.ai.mapper.AiConversationMapper;
import com.wave.wavesystem.ai.pojo.entity.AiConversation;
import com.wave.wavesystem.ai.pojo.query.AiConversationQuery;
import com.wave.wavesystem.ai.service.IAiConversationMessageService;
import com.wave.wavesystem.ai.service.IAiConversationService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
@Slf4j
public class AiConversationServiceImpl extends ServiceImpl<AiConversationMapper, AiConversation>
        implements IAiConversationService {

    @Resource
    private IAiConversationMessageService messageService;

    @Override
    public QueryChain<AiConversation> getQueryChain(AiConversationQuery query) {
        QueryChain<AiConversation> queryChain = this.queryChain();
        queryChain.orderBy(AiConversation::getCreateTime, false);
        return queryChain;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clear(String conversationId) {
        try {
            // 1. 先删除消息记录
            boolean messagesRemoved = messageService.removeByConversationId(conversationId);
            if (!messagesRemoved) {
                throw new WaveException("会话消息删除失败");
            }

            // 2. 再删除会话记录
            boolean conversationRemoved = this.remove(
                    this.query().eq(AiConversation::getConversationId, conversationId)
            );

            if (!conversationRemoved) {
                throw new WaveException("会话记录删除失败");
            }
        } catch (Exception e) {
            // 确保所有异常都能触发回滚
            if (e instanceof WaveException) {
                throw e;
            }
            throw new WaveException(ErrorCode.ERROR, "会话清除报错");
        }
    }

    @Override
    public AiConversation queryByConversationId(String conversationId) {
        return this.queryChain().eq(AiConversation::getConversationId, conversationId).one();
    }

    @Override
    public String genConversationId() {
        return UUID.randomUUID().toString().toLowerCase() + "-" + System.currentTimeMillis();
    }

}
